package com.yanftch.stopcoding.test;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class CustomSwitch extends JPanel {

    private boolean isOn; // 开关状态

    public CustomSwitch() {
        setPreferredSize(new Dimension(60, 30));
        setBackground(Color.LIGHT_GRAY);
        setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        // 添加鼠标点击事件
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                isOn = !isOn; // 切换状态
                repaint(); // 重新绘制
            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        // 绘制开关背景
        if (isOn) {
            g.setColor(Color.GREEN);
        } else {
            g.setColor(Color.WHITE);
        }
        g.fillRoundRect(0, 0, getWidth(), getHeight(), 15, 15);

        // 绘制开关圆点
        g.setColor(Color.WHITE);
        int circleX = isOn ? getWidth() - 25 : 5;
        g.fillOval(circleX, 0, 30, 30);
    }

    public boolean isOn() {
        return isOn;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Custom Switch Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new FlowLayout());
            frame.setBackground(Color.BLACK);
            frame.setForeground(Color.BLACK);
            frame.setPreferredSize(new Dimension(400, 300));

            CustomSwitch customSwitch = new CustomSwitch();
            frame.add(customSwitch);
            frame.pack();
            frame.setVisible(true);
        });
    }
}
